package com.cgs.query.server.listener

import com.cgs.query.connection.ConnectionFactory
import com.cgs.query.event.QueryProjectEvent
import com.cgs.query.server.service.publicSqlPoolName
import com.cgs.query.service.IProject2DefineService
import com.cgs.query.service.IProjectErrorLogService
import com.cgs.query.service.IProjectLockLogService
import com.cgs.query.util.Utils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.ApplicationListener
import org.springframework.scheduling.annotation.Async

/**
 * 项目监听：
 * 当项目进行删除时,删除定义以及connection
 * 当项目修改数据源时,删除connection
 */
open class QueryProjectListener : ApplicationListener<QueryProjectEvent> {

    @Autowired
    private lateinit var connectionFactory: ConnectionFactory
    @Autowired
    private lateinit var project2DefineService: IProject2DefineService
    @Autowired
    private lateinit var projectLockLogService: IProjectLockLogService
    @Autowired
    private lateinit var projectErrorLogService: IProjectErrorLogService

    @Async
    override fun onApplicationEvent(event: QueryProjectEvent?) {
        when (event?.type) {
            QueryProjectEvent.Type.DELETE -> {
                connectionFactory.removeConnection(event.projectName)
                //删除关联数据
                project2DefineService.deleteByProjectName(event.projectName)

                projectErrorLogService.deleteByProjectName(event.projectName)
            }
            QueryProjectEvent.Type.UPDATE -> {
                if (event.originQueryProject != null && event.originQueryProject?.sourceId != event.newQueryProject?.sourceId) {
                    connectionFactory.removeConnection(event.originQueryProject!!.name)
                }
                if (event.originQueryProject != null && event.newQueryProject != null) {
                    projectLockLogService.save(event.originQueryProject!!, event.newQueryProject!!, event.userId)
                }
            }
            QueryProjectEvent.Type.LOCK -> {
                projectLockLogService.save(event.originQueryProject!!, event.newQueryProject!!, event.userId)
            }
            QueryProjectEvent.Type.EXE_ERROR -> {
                if (event.projectName != publicSqlPoolName && event.projectName.isNotBlank()) {
                    Utils.notNullAndThen(event.e) {
                        projectErrorLogService.save(event.projectName, event.callName, event.e!!)
                    }
                }
            }
        }
    }
}